import UI from "./UI"

export default class HTTP {
    static Get(url: string, params = null, callback = null, showWait = true) {
        HTTP.request('GET', url, params, callback, showWait)
    }

    static Post(url: string, params = null, callback = null, showWait = true) {
        HTTP.request('POST', url, params, callback, showWait)
    }

    static request(method: string, url: string, params = null, callback = null, showWait = true) {
        method = method.toUpperCase()

        // let wait = null
        // if(showWait) {
        //     // TODO: 创建等待蒙版
        //     wait = UI.InitWindow('wait')
        // }

        let xhr = new XMLHttpRequest()
        xhr.timeout = 5000
        if (callback != null) {
            xhr.ontimeout = () => {
                callback(false)
            }

            xhr.onerror = () => {
                callback(false)
            }
        }

        // if(wait) {
        //     wait.destroy()
        // }

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 400) {
                    var response = xhr.responseText
                    callback(true, response)
                    if (CC_DEBUG) {
                        console.log(`${method} request url: ${url}, params: ${params}, result: ${response}`)
                    }
                } else {
                    callback(false)
                }
            }
        }

        let queryString = HTTP.QueryString(params)
        if (method == 'GET') {
            url = (url.endsWith('?') ? url : url + "?") + queryString
        }

        xhr.open(method, url, true)
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
        xhr.send(method == 'POST' ? queryString : null)
    }

    private static QueryString(params = {}) {
        if (!params) {
            return ''
        }

        let paramsString = ''
        for (let key in params) {
            paramsString += `${key}=${params[key]}&`
        }

        return paramsString
    }
}
